import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { CarbillEntity } from './entities/carbill.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { ListCarbillDto } from './dto';
import { UserDto } from '../user/user.decorator';
import { CarbillStatusEnum } from 'src/common/enum';

@Injectable()
export class CarbillService {
  constructor(
    @InjectRepository(CarbillEntity)
    private readonly carbillRep: Repository<CarbillEntity>,
  ) {}

  async findAll(query: ListCarbillDto, user: UserDto) {
    const entity = this.carbillRep.createQueryBuilder('carbill');
    const pageSize = query.pageSize || 10;
    const pageNum = query.pageNum || 1;
    const enterpriseId = user.enterpriseId;

    if (enterpriseId) {
      entity.andWhere(`carbill.enterpriseId = :enterpriseId`, { enterpriseId });
    }

    if (query.carbillStatus) {
      entity.andWhere('carbill.carbillStatus IN (:...carbillStatus)', { carbillStatus: query.carbillStatus });
    }

    entity.skip(pageSize * (pageNum - 1)).take(pageSize);
    entity.leftJoinAndSelect('carbill.driver', 'driver');
    entity.leftJoinAndSelect('driver.user', 'user');

    let [list, total] = await entity.getManyAndCount();
    const totalPage = Math.ceil(total / pageSize);
    return {
      list: list.map((item) => ({
        ...item,
        carbillStatus: CarbillStatusEnum[item.carbillStatus],
      })),
      total,
      totalPage,
      pageNum,
      pageSize,
    };
  }

  async findOne(carbillId: string, user: UserDto) {
    const entity = this.carbillRep.createQueryBuilder('carbill');
    entity.leftJoinAndSelect('carbill.driver', 'driver');
    entity.andWhere('carbill.enterpriseId = :enterpriseId', { enterpriseId: user.enterpriseId });
    entity.andWhere('carbill.carbillId = :carbillId', { carbillId });
    const result = await entity.getOne();
    return result;
  }
}
